<?php
/**
 * 预约
 **/
namespace Xijie\Controller;
use Think\Controller;

class YuyueController extends Controller {

	/**
	 * 房间宣传详情
	 *
	 **/
	public function index(){
		$usid = session('usid') ? (int)session('usid') : 0;
		if(!empty($usid)){
			$room_type = I('room_type', 'D1');
			//获取登陆用户信息
			$info = M('room_profile')->where(array('room_type' => $room_type))->find();
			//获取该房型下总数
			$roomcount = M('room')->where(array('root_type' => $room_type))->count();
			//获取该房型下的租用用户
			$rentcount = M('member')->alias('member')
				->join('left join momoda_room as room on member.room_number = room.room_number')
				->where(array('member.visible' => 1, 'room.root_type' => $room_type))
				->count();
			$count = $roomcount - $rentcount;
			//判断用户是否已经预定该房型
			$order = M('yuyue_order')->where(array(
				'usid' => $usid,
				'status' => 1,
				'room_type' => $room_type,
				'visible' => 0
			))->order('orderid desc')->limit(1)->find();
			//如果存在
			$isOrder = 0;
			$sort = 0;
			if(count($order)){
				//查询前置排队人数
				$sort = M('yuyue_order')->where(array(
					'orderid' => array('lt', $order['orderid']),
					'room_type' => $room_type,
					'visible' => 0,
					'status' => 1
				))->count();
				$isOrder = 1;
			}
			//页面传参
			$this->assign('sort', $sort);
			$this->assign('isOrder', $isOrder);
			$this->assign('info', $info);
			$this->assign('count', $count);
			$this->assign('id', session('usid'));
			$this->assign('phone', session('15823214287'));

			$this->display('detail');
		}else{
			//跳转到登陆界面
			$this->display('login');
		}
	}

	//登陆用户
	public function login(){
		if(IS_GET){
			if(session('usid')){
				$this->index();
			}else{
				$room_type = I('get.room_type', 'D1');
				$this->assign('room_type', $room_type);
				$this->display('login');
			}
		}else{
			$phone = I('post.phone', '');
			$pwds = I('post.pwds', '');

			$uinfo = M('yuyue_member')->where(array(
				'phone' => $phone
			))->find();

			if(count($uinfo)){
				if($uinfo['pwds'] == MD5($pwds)){
					session('usid', $uinfo['usid']);
					session('phone', $uinfo['phone']);
					echo 1;
				}else{
					echo 0;
				}
			}else{
				echo 0;
			}
		}
	}
	
	//注册
	public function register(){
		if(IS_GET){
			if(session('usid')){
				$this->index();
			}else{
				$this->display('register');
			}
		}else{
			$phone = I('post.phone', '');
			$nickname = I('post.nickname', '');
			$code = I('post.code', '');
			$card = I('post.card', '');
			$pwds = I('post.pwds', '');

			if(empty($phone) || empty($code) || empty($card) || empty($pwds)){
				exit('3');
			}

			//判断是否已经注册
			$count = M('yuyue_member')->where(array(
				'phone' => $phone
			))->count();

			if($count){
				echo 2;
			}else{
				//获取验证码
				$codeinfo = M('member_code')->where(array(
					'phone' => $phone
				))->find();
				//判断验证码是否有效
				if((time() - $codeinfo['createtime'] > 900) || $code != $codeinfo['code']){
					echo 3;
				}else{
					$row = M('yuyue_member')->data(array(
						'phone' => $phone,
						'nickname' => $nickname,
						'card' => $card,
						'pwds' => md5($pwds)
					))->add();

					if($row !== false){
						echo 1;
						//设置session
						session('usid', $row);
						session('phone', $phone);
					}else{
						echo 0;
					}
				}
			}
		}
	}

	//获取验证码
	public function getcode(){
		$code = rand(100000,999999);
		$phone = I('get.phone', '');
		//根据手机号码查询验证码
		$codeinfo = M('member_code')->where(array(
			'phone' => $phone
		))->find();
		//判断是否存在验证码
		if(count($codeinfo)){
			if(time() - $codeinfo['createtime'] <= 900){
				echo 2;
			}else{
				M('member_code')->where(array(
					'phone' => $phone
				))->delete();
				//添加数据
				$row = M('member_code')->data(array(
					'phone' => $phone,
					'code' => $code,
					'createtime' => time()
				))->add();

				if($row !== false){
					$f = sendYuYueSMSMessage($phone, $code);
					echo $f ? 1 : 0;
				}else{
					echo 0;
				}
			}
		}else{
			$row = M('member_code')->data(array(
				'phone' => $phone,
				'code' => $code,
				'createtime' => time()
			))->add();

			if($row !== false){
				$f = sendYuYueSMSMessage($phone, $code);
				echo $f ? 1 : 0;
			}else{
				echo 0;
			}
		}
	}

	/**
	 * 订单详情
	 *
	 **/
	public function order(){
		$room_type = I('room_type', 'D1');
		$total = 500;
		if(IS_GET){
			$info = M('room_profile')->where(array('room_type' => $room_type))->find();
			//获取参数
			$usid = session('usid') ? (int)session('usid') : 0;
			$phone = session('phone') ? session('phone') : '';
			//获取用户信息
			$uinfo = M('yuyue_member')->where(array(
				'usid' => $usid,
				'phone' => $phone
			))->find();

			if(count($uinfo)){
				$this->assign('uinfo', $uinfo);
				$this->assign('info', $info);
				$this->assign('total', number_format($total, 2));
				$this->display('order');
			}else{
				$this->display('login');
			}
		}else{
			$ordersn = 'YU_'. time();
			//添加订单
			$orderData = array(
				'ordersn' => $ordersn,
				'point' => $total,
				'usid' => session('usid'),
				'status' => 0,
				'room_type' => $room_type,
				'createtime' => time()
			);
			//添加订单
			$row = M('yuyue_order')->data($orderData)->add();
			if($row !== false){
				echo $row;
			}else{
				echo 0;
			}
		}
	}

	//微信账单缴费
	public function weixinpay(){
		//获取参数
		$orderid = I('get.oid', 0);
		//获取订单详情
		$orderInfo = M('yuyue_order')->where(array(
			'orderid' => $orderid
		))->find();
		
		if(count($orderInfo)){
			$ordersn = $orderInfo['ordersn'];
			$costorderTotal = $orderInfo['point'];
			//账单生成成功后调用支付方式
			import("Org.Util.JsApiPay");
			$jsApi = new \JsApiPay();
			$openid = $jsApi->GetOpenid();
			
			//设置支付参数
			$input = new \WxPayUnifiedOrder();
			$input->SetBody("定金");
			$input->SetOut_trade_no($ordersn);
			$input->SetTotal_fee($costorderTotal * 100);
			$input->SetTime_start(date("YmdHis"));
			$input->SetTime_expire(date("YmdHis", time() + 600));
			$input->SetNotify_url("http://mamagy.com/xj/yuyue/wxnotify.html"); //回调函数
			$input->SetTrade_type("JSAPI");
			$input->SetOpenid($openid);
			//统一订单
			$order = \WxPayApi::unifiedOrder($input);
			
			//获取JS参数
			$param = $jsApi->GetJsApiParameters($order);
			//getPrepayId
			$this->assign('jsApiParameters', $param);
			$this->assign('desc', '租房定金');
			$this->assign('total_fee', $costorderTotal);

			$this->display('Wap/wxpay');
		}else{
			exit;
		}	
	}

	//支付宝账单缴费
	public function alipay(){
		//获取参数
		$orderid = I('get.oid', 0);
		//获取合并后的订单
		//获取订单详情
		$orderInfo = M('yuyue_order')->where(array(
			'orderid' => $orderid
		))->find();
		
		if(count($orderInfo)){
			$array = array(
				"out_trade_no" => $orderInfo['ordersn'],
				"total_amount" => $orderInfo['point'],
				"product_code" => 'QUICK_WAP_WAY',
				"subject"      => '租房定金',
				"body"         => '租房定金'
			);
			
			$result = D('Alipay')->createWapAction($array, 'http://mamagy.com/xj/yuyue/alinotify.html');
		}
	}
	
	/**
	 * 微信支付回调
	 **/
	public function wxnotify(){
		$string = file_get_contents("php://input");
		$file_get_contents = (array)simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA);
		$result_code = $file_get_contents['result_code'];
		if($result_code == 'SUCCESS' && $file_get_contents['return_code'] == 'SUCCESS'){
			$out_trade_no = $file_get_contents['out_trade_no'];
			//获取订单详情
			$orderInfo = M('yuyue_order')->where(array(
				'ordersn' => $out_trade_no
			))->find();
			if($orderInfo['status'] == 0){
				$row = M('yuyue_order')->where(array('ordersn' => $out_trade_no))->setField(array(
					'status' => 1,
					'paymethod' => '微信'
				));
				
				if($row !== false){
					//获取用户信息
					$userinfo = M('yuyue_member')->where(array('usid' => $orderInfo['usid']))->find();
					//新增GoBackLog数据
					$go_data = array(
						'typeid' => 1,
						'contract' => '',
						'userid' => 0,
						'nickname' => $userinfo['nickname'],
						'roomnumber' => '',
						'deposit_first' => $file_get_contents['total_fee']/100,
						'acount' => $file_get_contents['total_fee']/100,
						'pay_type' => 2,
						'pay_card' => $file_get_contents['openid'],
						'createtime' => time(),
						'remark' => '租房定金',
						'status' => 1,
						'weixin' => $file_get_contents['total_fee']/100,
						'weixin_ordersn' => $file_get_contents['transaction_id']
					);
					
					$row = D('Gobacklog')->addGobacklogInfo($go_data);
					//返回状态
					$data = array('return_code' => '<![CDATA[SUCCESS]]>', 'return_msg' => '<![CDATA[OK]]>');
				}else{
					$data = array('return_code' => '<![CDATA[FAIL]]>', 'return_msg' => '<![CDATA[OK]]>');
				}
			}
		}else{
			$data = array('return_code' => '<![CDATA[FAIL]]>', 'return_msg' => '<![CDATA[OK]]>');
		}
		
		$this->response($data, 'json');
	}
	
	/**
	 * 支付宝回调
	 **/
	public function alinotify(){
		$string = file_get_contents("php://input");
		$discount = I('post.discount'); //折扣价
		$trade_no = I('post.trade_no'); //支付宝交易号
		$buyer_id = I('post.buyer_id'); //买家ID
		$buyer_email = I('post.buyer_email'); //买家支付账号
		$out_trade_no = I('post.out_trade_no'); //订单号
		$seller_id = I('post.seller_id'); //卖家账号ID
		$seller_email = I('post.seller_email'); //卖家账号
		$total_fee = I('post.invoice_amount'); //支付金额
		$gmt_payment = urldecode(I('gmt_payment')); //支付时间
		$trade_status = I('post.trade_status'); //订单状态 TRADE_SUCCESS 支付成功 WAIT_BUYER_PAY 创建订单成功 TRADE_FINISHED 订单结束
		$notify_id = I('post.notify_id'); //通知校验ID
		
		if(D('Alipay')->checkAlipayNotifyId($notify_id)){
			//获取订单详情
			$orderInfo = M('yuyue_order')->where(array(
				'ordersn' => $out_trade_no
			))->find();
			if($orderInfo['status'] == 0){
				//修改订单状态
				$row = M('yuyue_order')->where(array('ordersn' => $out_trade_no))->setField(array(
					'status' => 1,
					'paymethod' => '支付宝'
				));
				
				if($row !== false){
					//用户详情
					$userinfo = M('yuyue_member')->where(array('usid' => $orderInfo['usid']))->find();
					//新增GoBackLog数据
					if(is_array($userinfo) && count($userinfo)){
						$go_data = array(
							'typeid' => 1,
							'contract' => '',
							'userid' => 0,
							'nickname' => $userinfo['nickname'],
							'roomnumber' => '',
							'deposit_first' => $total_fee,
							'acount' => $total_fee,
							'pay_type' => 2,
							'pay_card' => $buyer_email,
							'createtime' => time(),
							'remark' => '租房定金',
							'status' => 1,
							'alipay' => $total_fee,
							'alipay_ordersn' => $trade_no
						);
						
						$row = D('Gobacklog')->addGobacklogInfo($go_data);
					}
					
					echo 1;
				}else{
					echo 0;
				}	
			}
		}else{
			echo 0;
		}
	}
	
	//后台列表
	public function lists(){
		$page = I('get.page') ? (int)I('get.page') : 1;
		$ajax = I('get.ajax') ? (int)I('get.ajax') : 0;
		//昵称
		$nickname = I("get.nick", "");
		if(!empty($nickname)){
			$param['nick'] = $nickname;
			$where['us.nickname'] = array('like', '%'. $nickname . '%');
		}
		
		//开始时间与结束时间
		$param['btime'] = $btime = I('get.btime', 0);
		$param['etime'] = $etime = I('get.etime', 0);
		if(!empty($btime) && empty($etime)){
			$where['ord.createtime'] = array('egt', strtotime($btime . ' 00:00:00'));
		}

		if(empty($btime) && !empty($etime)){
			$where['ord.createtime'] = array('elt', strtotime($etime . ' 23:59:59'));
		}

		if(!empty($btime) && !empty($etime)){
			$where['ord.createtime'] = array('between', array(
				strtotime($btime .' 00:00:00'),
				strtotime($etime .' 23:59:59')
			));
		}
		
		//设置状态
		$where['ord.status'] = 1;
		//获取总数
		$count = M('yuyue_order')->alias('ord')
						->join('left join momoda_yuyue_member as us on ord.usid = us.usid')
						->where($where)
						->count();
		//用户列表
		$userlist = M('yuyue_order')->alias('ord')
						->join('left join momoda_yuyue_member as us on ord.usid = us.usid')
						->where($where)
						->order('ord.orderid desc')
						->page($page, C('PAGE_SIZE'))
						->select();
		//页面赋值
		$this->assign('userlist', $userlist);
		$this->assign('count', $count);
		$this->assign('page', $page);

		if(is_array($param)){
			$this->assign('param', json_encode($param));
		}
		//判断请求方式
		if(!$ajax){
			$this->display('lists');
		}else{
			$this->display('list_table', 'utf-8', 'html');
		}
	}

	/**
	 * 编辑订单状态
	 **/
	public function editvisible(){
		$orderid = I('orderid', 0);
		$visible = I('visible', 0);

		$row = M('yuyue_order')->where(array(
			'orderid' => $orderid
		))->setField(array(
			'visible' => $visible
		));

		if($row !== false){
			echo 1;
		}else{
			echo 0;
		}
	}
}

